import html2canvas from '@wtto00/html2canvas';
import { embedMessageInMetadata } from './imageMetadata';
import piexif from 'piexifjs';

/**
 * 导出打印模板为图片
 * @param {Object} hiprintTemplate - hiprint模板实例
 * @returns {Promise} - 返回一个Promise，完成后自动下载图片
 */
/**
 * 从图片文件导入模板
 * @param {File} file - 图片文件
 * @param {Function} onSuccess - 成功回调，参数为模板数据
 * @param {Function} onError - 错误回调，参数为错误信息
 */
export function importTemplateFromImage(file) {
  return new Promise((resolve, reject) => {
    if (file.type !== 'image/jpeg') {
      reject(new Error('请上传JPEG格式的图片！'));
      return;
    }

    const reader = new FileReader();
    reader.onload = (event) => {
      const arrayBuffer = event.target.result;
      const binaryData = arrayBufferToBinaryString(arrayBuffer);

      try {
        const exifData = piexif.load(binaryData);
        const userComment = exifData.Exif[piexif.ExifIFD.UserComment];

        if (userComment && userComment !== '') {
          const decodedMessage = decodeURIComponent(userComment);
          const templateData = JSON.parse(decodedMessage);
          resolve(templateData);
        } else {
          reject(new Error('模板文件解析失败'));
        }
      } catch (error) {
        console.error('解析失败', error);
        reject(new Error('解析失败，请确认上传的图片格式和内容！'));
      }
    };
    reader.readAsArrayBuffer(file);
  });
}

/**
 * 将ArrayBuffer转换为二进制字符串
 * @param {ArrayBuffer} buffer - ArrayBuffer数据
 * @returns {string} - 二进制字符串
 */
function arrayBufferToBinaryString(buffer) {
  const uint8Array = new Uint8Array(buffer);
  let binary = '';
  for (let i = 0; i < uint8Array.length; i++) {
    binary += String.fromCharCode(uint8Array[i]);
  }
  return binary;
}

/**
 * 导出打印模板为图片
 * @param {Object} hiprintTemplate - hiprint模板实例
 * @returns {Promise} - 返回一个Promise，完成后自动下载图片
 */
export function exportTemplateToImage(hiprintTemplate) {
  return new Promise((resolve, reject) => {
    // 显示加载状态
    const loadingModal = document.createElement('div');
    loadingModal.className = 'loading-modal';
    loadingModal.innerHTML = `
      <div class="loading-content">
        <div class="loading-spinner"></div>
        <div class="loading-message">正在生成模板...</div>
        <div class="loading-success" style="display: none;"></div>
        <img class="preview-image" style="display: none; max-width: 300px; margin-top: 10px;" id="previewImage">
      </div>
    `;

    // 添加样式
    const styleSheet = document.createElement('style');
    styleSheet.textContent = `
      .loading-modal {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 9999;
      }
      .loading-content {
        background: white;
        padding: 20px;
        border-radius: 8px;
        text-align: center;
      }
      .loading-spinner {
        border: 4px solid #f3f3f3;
        border-top: 4px solid #3498db;
        border-radius: 50%;
        width: 40px;
        height: 40px;
        animation: spin 1s linear infinite;
        margin: 0 auto 10px;
      }
      @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
      }
    `;

    document.head.appendChild(styleSheet);
    document.body.appendChild(loadingModal);

    // 获取当前模板的JSON数据
    const templateJson = hiprintTemplate.getJson();

    // 获取模板的实际尺寸（毫米转像素，假设96dpi）
    const mmToPx = 3.78; // 1mm ≈ 3.78px (96dpi)
    const templateWidth = templateJson.panels[0].width * mmToPx;
    const templateHeight = templateJson.panels[0].height * mmToPx;

    // 提取所有字段和测试数据
    const printData = {};
    templateJson.panels.forEach(panel => {
      panel.printElements.forEach(element => {
        if (element.options && element.options.field) {
          printData[element.options.field] = element.options.testData || '';
        }
      });
    });

    // 将printData包装成数组
    const printDataArray = [printData];

    // 生成HTML
    const $html = hiprintTemplate.getHtml(printDataArray);

    // 创建临时容器
    const wrapper = document.createElement('div');
    wrapper.id = 'html-container';
    wrapper.style.cssText = `
      position: fixed;
      left: 0;
      top: 0;
      width: ${templateWidth}px;
      height: ${templateHeight}px;
      background: #fff;
      z-index: -9999;
      opacity: 1;
      visibility: visible;
    `;

    // 移除网格背景和优化样式
    const containerStyle = document.createElement('style');
    containerStyle.textContent = `
      #html-container .hiprint-printTemplate {
        background-image: none !important;
        background-color: #fff !important;
        margin: 0 !important;
        padding: 0 !important;
        box-shadow: none !important;
      }
      #html-container * {
        visibility: visible !important;
        opacity: 1 !important;
      }
    `;
    document.head.appendChild(containerStyle);

    // 将HTML内容插入并确保正确渲染
    wrapper.innerHTML = $html.prop('outerHTML');
    document.body.appendChild(wrapper);

    // 确保所有图片和字体加载完成
    const images = wrapper.getElementsByTagName('img');
    const imagePromises = Array.from(images).map(img => {
      return new Promise((resolve, reject) => {
        if (img.complete) {
          resolve();
        } else {
          img.onload = resolve;
          img.onerror = reject;
        }
      });
    });

    // 等待字体加载
    const fontPromise = document.fonts ? document.fonts.ready : Promise.resolve();

    // 等待所有资源加载完成后再生成图片
    Promise.all([fontPromise, ...imagePromises]).then(() => {
      html2canvas(wrapper, {
        width: templateWidth,
        height: templateHeight,
        backgroundColor: '#fff',
        scale: 2,
        useCORS: true,
        logging: true,
        allowTaint: true,
        foreignObjectRendering: true,
        onclone: function(clonedDoc) {
          const clonedWrapper = clonedDoc.getElementById('html-container');
          if (clonedWrapper) {
            clonedWrapper.style.visibility = 'visible';
            clonedWrapper.style.opacity = '1';
          }
        }
      }).then(canvas => {
        try {
          const imgData = canvas.toDataURL('image/jpeg', 0.9);
          const base64WithMessage = embedMessageInMetadata(imgData, encodeURIComponent(JSON.stringify(templateJson)));

          // 显示预览图片
          const previewImage = document.getElementById('previewImage');
          previewImage.src = imgData;
          previewImage.style.display = 'block';

          // 下载图片
          const link = document.createElement('a');
          link.href = base64WithMessage;
          link.download = 'template_' + new Date().getTime() + '.jpeg';
          link.click();

          // 显示成功消息
          document.querySelector('.loading-spinner').style.display = 'none';
          document.querySelector('.loading-message').style.display = 'none';
          document.querySelector('.loading-success').textContent = '模板生成成功！';
          document.querySelector('.loading-success').style.display = 'block';

          // 3秒后关闭加载框
          setTimeout(() => {
            document.body.removeChild(loadingModal);
            document.body.removeChild(wrapper);
            document.head.removeChild(styleSheet);
            document.head.removeChild(containerStyle);
            resolve();
          }, 3000);
        } catch (error) {
          reject(error);
        }
      }).catch(error => {
        reject(error);
      });
    }).catch(error => {
      console.error('Resource loading error:', error);
      reject(error);
    });
  });
}